package com.sukaiyi.generator.ui;

import com.sukaiyi.generator.config.PluginConfig;
import com.sukaiyi.generator.config.model.StructTemplate;
import com.sukaiyi.generator.config.model.TplType;
import com.intellij.ui.ColoredListCellRenderer;
import com.intellij.ui.JBColor;
import com.intellij.ui.SimpleTextAttributes;
import icons.PluginIcons;
import org.jetbrains.annotations.NotNull;

import javax.swing.*;
import java.awt.event.ItemListener;
import java.util.LinkedList;
import java.util.List;
import java.util.Queue;

import static com.intellij.ui.SimpleTextAttributes.STYLE_PLAIN;

public class TemplateComboBox {

    private JComboBox<StructTemplate> templateComboBox;
    private JPanel rootPanel;
    private PluginConfig pluginConfig = PluginConfig.getInstance();

    public TemplateComboBox() {
        templateComboBox.setModel(new DefaultComboBoxModel<>(pluginConfig.templates.toArray(new StructTemplate[]{})));
        templateComboBox.setRenderer(new ColoredListCellRenderer<StructTemplate>() {
            @Override
            protected void customizeCellRenderer(@NotNull JList<? extends StructTemplate> list, StructTemplate value, int index, boolean selected, boolean hasFocus) {
                setIcon(PluginIcons.FAST);
                setIconTextGap(5);
                append(value.getName());
                int folderNum = 0;
                int fileNum = 0;
                Queue<StructTemplate> queue = new LinkedList<>();
                List<StructTemplate> pChildren = value.getChildren();
                if (pChildren != null && pChildren.size() > 0) {
                    queue.addAll(pChildren);
                }
                while (!queue.isEmpty()) {
                    StructTemplate template = queue.poll();
                    if (template.getType() == TplType.MODULE) {
                        folderNum++;
                        List<StructTemplate> children = template.getChildren();
                        if (children != null) {
                            queue.addAll(children);
                        }
                    } else {
                        fileNum++;
                    }
                }
                append(String.format("    %s folders and %s files", folderNum, fileNum), new SimpleTextAttributes(STYLE_PLAIN, JBColor.gray));
            }
        });
    }

    public void addItemListener(ItemListener listener) {
        templateComboBox.addItemListener(listener);
    }

    public void updateUI() {
        templateComboBox.setModel(new DefaultComboBoxModel<>(pluginConfig.templates.toArray(new StructTemplate[]{})));
    }

    public StructTemplate getSelectedItem() {
        return (StructTemplate) templateComboBox.getSelectedItem();
    }
}
